package com.daykw.douyin.task;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.impl.NutDao;

import com.daykw.douyin.config.NutzDaoConfig;
import com.daykw.douyin.http.HttpBase;
import com.daykw.douyin.model.VideoInfo;
import com.daykw.douyin.utils.SpringContextHolder;

public class VideoExtThread extends Thread {

	private static Logger logger = Logger.getLogger(VideoExtThread.class);
	private SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");

	public void doWork() {
		try {
			NutDao dao = SpringContextHolder.getBean(NutzDaoConfig.class);
			List<VideoInfo> tasks = dao.query(VideoInfo.class,
					Cnd.where("kw_url", "is not", null).and("playaddr", "is", null).limit(1, 50));

			HttpBase http = new HttpBase();
			// Map<String, String> headers = new HashMap<String, String>();
			Map<String, String> headers = new HashMap<String, String>();
			headers.put("Host", "www.douyin.com");
			headers.put("Cookie",
					"tt_webid=6691236382550132231; _ba=BA0.2-20190515-5199e-YA78J2KirK06A2k9WJ9l; _ga=GA1.2.530997447.1557925129; _gid=GA1.2.93745010.1559057701");

			for (VideoInfo task : tasks) {
				String url = task.getKw_url().replace("https", "http");
				String html = http.get(url, null);
				Document doc = Jsoup.parse(html);
				Elements scripts = doc.getElementsByTag("script");
				String playaddr = null;
				for (Element s : scripts) {

					String script = s.toString();
					if (script.indexOf("playAddr") > 0) {
						String[] sc = script.split("\r\n");

						for (String row : sc) {
							if (row.indexOf("playAddr") > 0) {
								// var url = '/Aweme/GetComment?uid=63625792717' +
								// '&awemeId=6678156513263111432' + '&page=1';
								playaddr = row.substring(row.indexOf("\"") + 1, row.lastIndexOf("\""));

								break;
							}

						}

					}
				}

				if (StringUtils.isNotEmpty(playaddr)) {
					dao.update(VideoInfo.class,
							Chain.make("playaddr", playaddr).add("udate", Long.parseLong(fmt.format(new Date()))),
							Cnd.where("id", "=", task.getId()));
				} else {
					dao.update(VideoInfo.class, Chain.make("playaddr", "视频找不到了，看看其他精彩作品吧！").add("udate",
							Long.parseLong(fmt.format(new Date()))), Cnd.where("id", "=", task.getId()));
				}
				int time = this.getRnum(3) * 1000;
				int sleep = time;
				Thread.sleep(sleep);
				logger.info("playaddr:" + playaddr);
			}

		} catch (Exception e) {
			logger.error("", e);
		}

	}

	private int getRnum(int max) {
		int x = (int) (Math.random() * max);
		return x;
	}

	@Override
	public void run() {

		doWork();

//		try {
//			NutDao dao = SpringContextHolder.getBean(NutzDaoConfig.class);
//
//			List<VideoTask> tasks = dao.query(VideoTask.class, Cnd.where("ext_status", "=", 0).limit(1, 10));
//
//			HttpBase http = new HttpBase();
//			Map<String, String> headers = new HashMap<String, String>();
//			String cookie = dao.fetch("t_cookie", Cnd.where("name", "=", "大斌")).getString("cookie");
//
//			for (VideoTask task : tasks) {
//
//				VideoInfo video = dao.fetch(VideoInfo.class, Cnd.where("kw_id", "=", task.getKw_id()));
//
//				Map<String, String> data = new HashMap<String, String>();
//				data.put("promotionId", "");
//				data.put("id", video.getDataid());
//				data.put("awemeid", video.getKw_id());
//				headers.put("Cookie", cookie);
//				try {
//					String html = http.post("https://dsp.feigua.cn/Aweme/GetFansAnalysis", headers, data);
//					if (html.equals("fail")) {
//						dao.update(VideoTask.class, Chain.make("ext_status", 3),
//								Cnd.where("kw_id", "=", video.getKw_id()));
//						logger.error("抓取uid请求异常###########");
//						continue;
//					}
//					Document doc = Jsoup.parse(html);
//					JSONObject json = new JSONObject();
//					JSONArray sexArr = new JSONArray();
//					Elements ges = doc.select("div.gender-text div.col-sm-6");
//					for (Element s : ges) {
//						JSONObject sjson = new JSONObject();
//						String val = s.text();
//						if (val.indexOf("男") >= 0) {
//							String[] sexs = val.split(" ");
//							sjson.put("sex", sexs[0]);
//							sjson.put("val", sexs[1]);
//						} else {
//							String[] sexs = val.split(" ");
//							sjson.put("sex", sexs[0]);
//							sjson.put("val", sexs[1]);
//						}
//						sexArr.add(sjson);
//					}
//					json.put("sex", sexArr);
//
//					Elements scripts = doc.getElementsByTag("script");
//					String age_data = null;
//					for (Element s : scripts) {
//
//						String script = s.toString();
//						if (script.indexOf("age_data") > 0) {
//							String[] sc = script.split("\r\n");
//
//							for (String row : sc) {
//								if (row.indexOf("age_data") > 0) {
//									// var url = '/Aweme/GetComment?uid=63625792717' +
//									// '&awemeId=6678156513263111432' + '&page=1';
//									age_data = row.substring(row.indexOf("["), row.lastIndexOf("]") + 1);
//
//									break;
//								}
//
//							}
//
//						}
//
//					}
//
//					if (StringUtils.isNotEmpty(age_data)) {
//						JSONArray age_arry = JSONArray.parseArray(age_data);
//						json.put("age", age_arry);
//					} else {
//						json.put("age", new JSONArray());
//					}
//
//					JSONArray areaArr = new JSONArray();
//					Elements trs = doc.select("table.location-table tr");
//					for (Element tr : trs) {
//						JSONObject ajson = new JSONObject();
//						Elements tds = tr.select("td");
//
//						ajson.put("area", tds.get(0).text());
//						ajson.put("val", tds.get(1).text());
//						areaArr.add(ajson);
//
//					}
//					json.put("area", areaArr);
//					dao.update(VideoInfo.class, Chain.make("ext_info", json.toJSONString()),
//							Cnd.where("kw_id", "=", task.getKw_id()));
//					dao.update(VideoTask.class, Chain.make("ext_status", 2), Cnd.where("kw_id", "=", video.getKw_id()));
//					logger.info("##########" + task.getKw_id() + ",其他数据抓完，暂停4秒");
//					Thread.sleep(4000);
//				} catch (Exception ee) {
//					logger.error("", ee);
//					dao.update(VideoTask.class, Chain.make("ext_status", 3), Cnd.where("kw_id", "=", video.getKw_id()));
//				}
//
//			}
//
//		} catch (Exception e) {
//
//			logger.error("", e);
//		}

	}
}
